﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using LogForParameter.Api.SwaggerHelp;
using ViewModels.Login;
using System.Security;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using LogForParameter.Api.GlobalHelp;
using LogForParameter.Api.JWTAuth;
using LogForParameter.Model.Models;
using SqlSugar.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using LogForParameter.Api.Common;
using Library.GlobalVars;
using LogForParameter.IServices;
using Library.Helper;

namespace LogForParameter.Api.Controllers
{
    //[Route("api/[controller]/[action]")]
    [CustomRoute(CustomApiVersion.MyApiVersion.Business)]
    //[Authorize(Permissions.Name)]
    [ApiController]
    public class LoginPowerController : ControllerBase
    {
        private readonly IHttpContextAccessor _accessor;
        public IHttpContextAccessor HttpContextAccessor { get; set; }
        private readonly ILogger<LoginPowerController> _log;
        private readonly PermissionRequirement _requirement;
        //private readonly VillageOfficial _test;
        public LoginPowerController(ILogger<LoginPowerController> logger, IHttpContextAccessor httpContextAccessor, PermissionRequirement requirement)
        {
            _log = logger;
            _accessor = httpContextAccessor;
            _requirement = requirement;
        }
        /// <summary>
        /// 根据模块id获取菜单列表
        /// </summary>
        /// <param name="modularItem">0:全部模块菜单 1：儿童之家管理2：儿童之家驾驶舱 3：儿童同之家数据仓库 4：儿童之家其他模块 5：儿童之家视频对接</param>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "GetMenuListByModularItem")]
        [HttpGet]
        [Authorize(Policy = "AdminOrWorker")]
        public OutPut GetMenuListByModularItem(string modularItem)
        {
            string hosid = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        /// <summary>
        /// 获取角色对应菜单id集合
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "GetRoleMenuSelectItem")]
        [HttpGet]
        [Authorize]
        public OutPut GetRoleMenuSelectItem(string roleId)
        {
            string hosId = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        /// <summary>
        /// 保存角色对应所有菜单id
        /// </summary>
        /// <param name="roleinfo"></param>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "SaveRoleMenuSelectItem")]
        [HttpPost]
        [Authorize(Policy = "A_S_O")]
        public OutPut SaveRoleMenuSelectItem(AddRole roleinfo)
        {
            string hosId = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "GetUserRoles")]
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public OutPut GetUserRoles()
        {
            string hosId = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "AddUser")]
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public OutPut AddUser(addUser user)
        {
            string jobNumber = GetHeader.GetJobNumber(Request.Headers);
            string hosId = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "ChangeUser")]
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public OutPut ChangeUser(addUser user)
        {
            string jobNumber = GetHeader.GetJobNumber(Request.Headers);
            string hosId = GetHeader.GetHosId(Request.Headers);
            return Public.NewOP_Ok("");
        }
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "GetToken")]
        [HttpGet]
        public ActionResult<IEnumerable<string>> GetToken()
        {
            string testRole = GetHeader.GetRole(Request.Headers);
            string defaultRole = "Admin";
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name,"lixiaoyao"),
                new Claim(ClaimTypes.Role,defaultRole),
                new Claim(ClaimTypes.Role,testRole),
                new Claim(JwtRegisteredClaimNames.Email,"1583044952@qq.com"),
                new Claim(JwtRegisteredClaimNames.Sub,"1"),//主题id
            };
            //生成对称秘钥
            var key16 = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("lixiaoyaozaoshangqichuangdayuanshen"));//16位至少
            //创建token对象
            var token = new JwtSecurityToken(
                issuer: "HTTP://SEND.COM",//发起者
                audience: "HTTP://RECEIVE.COM",//接收者
                claims: claims,
                expires: DateTime.Now.AddMinutes(60),
                signingCredentials: new SigningCredentials(key16, SecurityAlgorithms.HmacSha256)
                );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return new string[] { jwtToken };
        }
        [HttpGet]
        [CustomRoute(CustomApiVersion.MyApiVersion.Business, "GetTokenContent")]
        //[Authorize(Permissions.Name)]
        [Authorize(Policy = "AdminAndWork")]
        public ActionResult<IEnumerable<string>> GetTokenContent(string jwtStr)
        {
            // 获取token内容的方法
            //1
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);

            //2
            var sub = User.FindFirst(d => d.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;

            //3
            var name = _accessor.HttpContext.User.Identity.Name;
            var claims = _accessor.HttpContext.User.Claims;
            var claimTypeVal = (from item in claims
                                where item.Type == JwtRegisteredClaimNames.Email
                                select item.Value).ToList();

            return new string[] { JsonConvert.SerializeObject(jwtToken), sub, name, JsonConvert.SerializeObject(claimTypeVal) };
        }

        /// <summary>
        /// 获取JWT的方法3：整个系统主要方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<TokenInfoViewModel>> GetJwtToken3(string name = "", string pass = "")
        {
            try
            {
                string jwtStr = string.Empty;
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass))
                {
                    return new MessageModel<TokenInfoViewModel>()
                    {
                        success = false,
                        msg = "用户名或密码不能为空",
                    };
                }
                pass = MD5Helper.MD5Encrypt32(pass);
                //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, name),
                    new Claim(JwtRegisteredClaimNames.Jti,"1"),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()),new Claim(ClaimTypes.Role, "Worker"), new Claim(ClaimTypes.Role, "Admin") };
                ////用户标识
                //var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                //identity.AddClaims(claims);
                // ids4和jwt切换
                // jwt
                if (!Permissions.IsUseIds4)
                {
                    var date = await Task.Run(() => { var a = 1 + 1; return a; });
                    //var data = await _login.GetRoleModulePermisions();
                    var list = new List<PermissionItem>();
                    //list = (from item in data
                    //        where item.IsDeteted == false
                    //        orderby item.ID
                    //        select new PermissionItem
                    //        {
                    //            Url = item.Module?.LinkUrl,
                    //            Role = item.Role?.Name.ObjToString(),
                    //        }).ToList();
                    _requirement.Permissions = list;
                }
                var token = JWTTokenHelp.BuildJwtToken(claims.ToArray(), _requirement);
                return new MessageModel<TokenInfoViewModel>()
                {
                    success = true,
                    msg = "获取成功",
                    response = token
                };
            }
            catch (Exception ex)
            {

                return new MessageModel<TokenInfoViewModel>()
                {
                    success = false,
                    msg = ex.Message,
                };
            }
        }
        /// <summary>
        /// 请求刷新Token（以旧换新）
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        //[Route("RefreshToken")]
        public async Task<MessageModel<TokenInfoViewModel>> RefreshToken(string token = "")
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(token))
            {
                return new MessageModel<TokenInfoViewModel>()
                {
                    success = false,
                    msg = "token无效，请重新登录！",
                };
            }
            var tokenModel = JwtHelper.SerializeJwt(token);
            if (tokenModel != null && JwtHelper.CustomSafeVerify(token) && tokenModel.Uid > 0)
            {
                var date = await Task.Run(() => { var a = 1 + 1; return a; });
                //var data = await _login.GetRoleModulePermisions();
                var list = new List<PermissionItem>() { new PermissionItem { Url = "", Role = "Admin" }, new PermissionItem { Url = "", Role = "System" } };
                //list = (from item in data
                //        where item.IsDeteted == false
                //        orderby item.ID
                //        select new PermissionItem
                //        {
                //            Url = item.Module?.LinkUrl,
                //            Role = item.Role?.Name.ObjToString(),
                //        }).ToList();
                _requirement.Permissions = list;
                //if (user != null)
                //{
                //var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(user.uLoginName, user.uLoginPWD);
                //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name,"FX"),
                    new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()),
                    new Claim(ClaimTypes.Role, "System"), new Claim(ClaimTypes.Role, "Admin")};
                //claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

                //用户标识
                //var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                //identity.AddClaims(claims);

                var refreshToken = JWTTokenHelp.BuildJwtToken(claims.ToArray(), _requirement);
                return new MessageModel<TokenInfoViewModel>()
                {
                    success = true,
                    msg = "获取成功",
                    response = refreshToken
                };
            }
            else
            {
                return new MessageModel<TokenInfoViewModel>()
                {
                    success = false,
                    msg = "认证失败！",
                };
            }
        }
    }
}
